/*
 * =====================================================================================
 *
 *       Filename:  subscribe.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2019年06月03日 08时57分46秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  YOUR NAME (), 
 *   Organization:  
 *
 * =====================================================================================
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <fcntl.h>

const char *server_path = "/home/kylin/server.unix";
const char *client_path = "/home/kylin/client.unix";

int subscribe_init()
{
    /* 订阅 */
    int fd = socket(AF_LOCAL, SOCK_DGRAM, 0);
    if(fd < 0) {
        perror("socket()");
        return -1;
    }
    struct sockaddr_un client_un;
    socklen_t client_len = sizeof(client_un);
    memset(&client_un, 0, sizeof(client_un));
    client_un.sun_family = AF_LOCAL;
    strncpy(client_un.sun_path, client_path, sizeof(client_un.sun_path) - 1);

#if 1
    unlink(client_path);
    if(bind(fd, (struct sockaddr *)&client_un, client_len) < 0) {
        perror("bind()");
        close(fd);
        return -1;
    }
#endif

    return fd;
}

int main(int argc, char **argv)
{
    int fd = subscribe_init();
    if(fd < 0) {
        return -1;
    }
    struct sockaddr_un server_un;
    socklen_t server_len = sizeof(server_un);
    memset(&server_un, 0, sizeof(server_un));
    server_un.sun_family = AF_LOCAL;
    strncpy(server_un.sun_path, server_path, sizeof(server_un.sun_path) - 1);

    while(1) {
        char *msg = "Hello Unix Server.";
        int ret = sendto(fd, msg, strlen(msg), 0,
                         (struct sockaddr *)&server_un, sizeof(server_un)); 

        char buff[1024] = {0};
        ret = recvfrom(fd, buff, sizeof(buff) - 1, 0,
                       (struct sockaddr *)&server_un, &server_len);
        if(ret < 0) {
            perror("recvfrom()");
            continue;
        }
        printf("recv: [%s]\n", buff);
    }
    return 0;
}


